<template>
    <div class="category">
        <van-nav-bar title="分类" />
        <div class="treeSelect">
            <div class="left_list" ref="leftListRef">
                <div v-for="(item, i) in categoryList" :key="i" :class="{ active: currentIndex === i }"
                    class="left_list_item" @click="clickList(i)">
                    {{ item.name }}
                </div>
            </div>
            <div class="right_list menu-right" ref="rightListRef">
                <div class="right_list_content">
                    <div v-for="item in categoryList" class="right_list_item">
                        <h4>{{ item.name }}</h4>
                        <div class="item_children">
                            <div v-for="child in item.children" class="item_children_item"
                                @click="router.push({ path: `/product/${child.id}` })">
                                <van-image width="80" height="80" fit="cover" :src="child.picture" />
                                <p>{{ child.name }}</p>
                            </div>
                        </div>
                    </div>
                    <div class="bottom"></div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, computed } from 'vue';
import { getCategoryListService } from '@/apis/category'
import { useRouter } from 'vue-router';
import BScroll from '@better-scroll/core'
const router = useRouter();
const categoryList = ref([])
const getCategoryList = async () => {
    let res = await getCategoryListService();
    // 处理数据
    let data = res.data.filter(item => {
        return item.pid == 0;
    })
    data.forEach(item => {
        item.children = res.data.filter(child => {
            return child.pid == item.id;
        });
    })
    categoryList.value = format(data);
}
const format = (items, parentIndex = '') => {
    let index = 1;
    return items.map((item, i) => {
        const currentIndex = parentIndex ? `${parentIndex}${i + 1}` : `${index++}`;
        const formattedItem = { ...item, index: currentIndex };
        if (item.children) {
            formattedItem.children = format(item.children, `${currentIndex}0`);
        }
        return formattedItem;
    });
};

// 左右联动
const rightListRef = ref()
const rightTops = ref([])
const leftListRef = ref()
const scrollY = ref(0)
let leftBscroll = null
let rightBscroll = null

onMounted(() => {
    getCategoryList();
    RightHeightFix()
})
// 监听
watch(categoryList, () => {
    nextTick(() => {
        initBScroll()
        initRightHeight()
    })
})
// 单击左侧菜单项
const clickList = index => {
    scrollY.value = rightTops.value[index]
    rightBscroll.scrollTo(0, -scrollY.value, 200)
}

// 初始化BScroll
const initBScroll = () => {
    // 初始化左菜单
    leftBscroll = new BScroll('.left_list', {
        click: true,
        mouseWheel: true
    })
    // 初始化右菜单
    rightBscroll = new BScroll('.menu-right', {
        click: true,
        mouseWheel: true,
        probeType: 3 // 实时派发scroll事件
    })
    rightBscroll.on('scroll', pos => {
        scrollY.value = Math.abs(pos.y)
    })
}

// 初始化右边菜单的高度
const initRightHeight = () => {
    const itemArray = []
    let top = 0
    itemArray.push(top)
    const allList = rightListRef.value.getElementsByClassName('right_list_item')
    Array.prototype.slice.call(allList).forEach(item => {
        top += item.clientHeight
        itemArray.push(top)
    })
    rightTops.value = itemArray
}

const RightHeightFix = () => {
    let bottom = rightListRef.value.getElementsByClassName('bottom')[0]
    bottom.style.height = rightListRef.value.clientHeight / 1.2 + 'px'
}

// 右菜单滚动时，左菜单联动
const initLeftScroll = index => {
    const menu = leftListRef.value.children
    let el = menu[index]
    leftBscroll.scrollToElement(el, 300, 0, -100)
}

// 监听数据的到达，并在回调函数中更新
const currentIndex = computed(() => {
    return rightTops.value.findIndex((top, index) => {
        if (index === rightTops.value.length - 2) {
            return true
        }
        if (scrollY.value >= top && scrollY.value < rightTops.value[index + 1]) {
            initLeftScroll(index)
            return true
        }
    })
})
</script>
<style scoped>
.category {
    overflow: hidden;
}

.treeSelect {
    display: flex;

}

.left_list {
    text-align: center;
    display: flex;
    flex-direction: column;
    background-color: #eee;

}

.left_list .left_list_item {
    cursor: pointer;
    font-size: 16px;
    padding: 15px 10px;
    color: #333;
    border-bottom: 1px solid #ccc;
}

.left_list .active {
    background-color: #fff;
}

.right_list {

    flex: 1;
    height: calc(100vh - 96px);
    background-color: #fff;
    padding: 10px;
}

.right_list_content {
    display: flex;
    flex-direction: column;
    row-gap: 20px;
}

.right_list .right_list_item {
    display: flex;
    flex-direction: column;
    row-gap: 10px;
    height: 100%;
}

.item_children {
    display: flex;
    row-gap: 10px;
    flex-wrap: wrap;
    justify-content: flex-start;
}

.item_children_item {
    flex: 0 0 33.33%;
    text-align: center;
}
</style>